import Request from '@/common/request/js_sdk/luch-request/luch-request/index.js';
import { ACCESS_TOKEN } from '@/common/utils/constants.js';
import store from '@/store/index.js';
import tool from '@/common/utils/tool.js';

// 读取配置文件api地址
let apiUrl = 'http://101.35.196.94:8088';//process.env.VUE_APP_API_HOST;
const getTokenStorage = () => {
	let token = ''
	try {
		if(store.state.token){
			return store.state.token;
		}
		return uni.getStorageSync(ACCESS_TOKEN);
	} catch (e) {
		//TODO handle the exception
		console.log("getTokenStorage", token)
	}
	return token
}

const http = new Request()
http.setConfig((config) => {
	/* 设置全局配置 */
	config.baseURL = apiUrl; /* 根域名不同 */
	config.header = {
		...config.header
	}
	return config;
});

/**
 * 自定义验证器，如果返回true 则进入响应拦截器的响应成功函数(resolve)，否则进入响应拦截器的响应错误函数(reject)
 * @param { Number } statusCode - 请求响应体statusCode（只读）
 * @return { Boolean } 如果为true,则 resolve, 否则 reject
 */
// 有默认，非必写
http.validateStatus = (statusCode) => {
	return statusCode === 200
}

http.interceptors.request.use((config, cancel) => {
	// uni.showLoading({title: '加载中'});
	/* 请求之前拦截器 */
	// const cookieValue = cookie.get('cookie');
	config.header = {
		...config.header,
		'X-Access-Token': getTokenStorage(),
		// 'Cookie': cookieValue
	}

	return config
});


// 必须使用异步函数，注意
http.interceptors.response.use(async (response) => {
	// uni.hideLoading();
	/* 请求之后拦截器 */
	if (response.statusCode === 200) { // 服务端返回的状态码不等于200，则reject()
		if (response.data.success !== true) {
			uni.showToast({
				title: `${response.data.code}:${response.data.message}`,
				duration: 2000,
				icon: 'none'
			});
			return Promise.reject(response)
		}
	}
	return response.data.result;
}, (error) => {
	if (error) {
		// uni.hideLoading();
		let data = error.data;

		switch (error.statusCode) {
			case 403:
				break
			case 500:
				uni.showToast({
					title: error.data.error.message,
					duration: 2000,
					icon: 'none'
				});
				break
			case 404:
				break
			case 400:

				uni.showToast({
					title: error.data.error.details,
					duration: 2000,
					icon: 'none'
				});

				break
			case 504:
				break
			case 401:
				tool.goToPage('/pages/Login/index','','reLaunch');
			// 	if (token) {
			// 		/* store.dispatch('Logout').then(() => {
			//   setTimeout(() => {
			// 	window.location.reload()
			//   }, 1500)
			// }) */
			// 	}
				break
			default:
				// tip.error({
				//   duration: 0,
				//   forbidClick: true,
				//   message: data.message
				// });
				break
		}
	}
	return Promise.reject(error);
})

export {
	http
}
